package com.gomtel.smartdevice.ui.activity;

import android.app.AlertDialog;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.gomtel.smartdevice.R;
import com.gomtel.smartdevice.base.WatchAppBaseActivity;
import com.gomtel.smartdevice.bean.UserContent;
import com.gomtel.smartdevice.global.DataClass;
import com.gomtel.smartdevice.moudle.db.entity.AppConfigurationInfo;
import com.gomtel.smartdevice.moudle.db.entity.SignsOfDataInfo;
import com.gomtel.smartdevice.moudle.event.CommonEvent;
import com.gomtel.smartdevice.moudle.event.EventCode;
import com.gomtel.smartdevice.moudle.rxtools.EventBusUtil;
import com.gomtel.smartdevice.ui.dialog.ShowDialog;
import com.gomtel.smartdevice.utils.CommonUtils;
import com.gomtel.smartdevice.utils.LogUtil;
import com.littlejie.circleprogress.DialProgress;

import java.text.NumberFormat;

import butterknife.BindView;

/**
 * Created by Administrator on 2018/5/18 0018.
 * 多类型界面
 */

public class MultiTypeActivity extends WatchAppBaseActivity implements View.OnClickListener {

    @BindView(R.id.img_btn_black)
    ImageButton img_btn_black;
    @BindView(R.id.title_name)
    TextView title_name;
    @BindView(R.id.devicename)
    TextView devicename;
    @BindView(R.id.mac_location)
    TextView mac_location;
    @BindView(R.id.unbundle)
    TextView unbundle;
    @BindView(R.id.unbundle_layout)
    RelativeLayout unbundle_layout;
    @BindView(R.id.goal_layout)
    RelativeLayout goal_layout;
    @BindView(R.id.commit)
    TextView commit;
    @BindView(R.id.pedometer)
    EditText pedometer;
    @BindView(R.id.calory_)
    EditText calory_;

    @BindView(R.id.about_layout)
    LinearLayout about_layout;
    @BindView(R.id.layout_app)
    RelativeLayout layout_app;
    @BindView(R.id.layout_device)
    RelativeLayout layout_device;
    @BindView(R.id.copy_right)
    TextView copy_right;
    @BindView(R.id.app_version)
    TextView app_version;
    @BindView(R.id.device_version)
    TextView device_version;
    @BindView(R.id.app_version_up)
    TextView app_version_up;
    @BindView(R.id.device_version_up)
    TextView device_version_up;

    @BindView(R.id.web_layout)
    FrameLayout web_layout;
    @BindView(R.id.web_view)
    WebView web_view;
    @BindView(R.id.progressbar)
    ProgressBar progressbar;

    @BindView(R.id.calory_layout)
    RelativeLayout calory_layout;
    @BindView(R.id.progress_calory_bar)
    DialProgress progress_calory_bar;
    @BindView(R.id.calory_standard)
    TextView calory_standard;

    @BindView(R.id.consume_calory)
    TextView consume_calory;
    @BindView(R.id.consume_calory_percentage)
    TextView consume_calory_percentage;

    @BindView(R.id.text_layout)
    RelativeLayout text_layout;
    @BindView(R.id.text_view)
    TextView text_view;

    @BindView(R.id.pulse_condition_layout)
    LinearLayout pulse_condition_layout;
    @BindView(R.id.title_content)
    TextView title_content;
    @BindView(R.id.type_mai)
    TextView type_mai;
    @BindView(R.id.type_mai_content)
    TextView type_mai_content;
    @BindView(R.id.type_zhengzhuang)
    TextView type_zhengzhuang;
    @BindView(R.id.type_zhengzhuang_content)
    TextView type_zhengzhuang_content;
    @BindView(R.id.type_pingfen)
    TextView type_pingfen;
    @BindView(R.id.type_pingfen_content)
    TextView type_pingfen_content;
    @BindView(R.id.jianyi_title)
    TextView jianyi_title;
    @BindView(R.id.jianyi_content)
    TextView jianyi_content;
    @BindView(R.id.jianyi_img)
    ImageView jianyi_img;

    private ShowDialog showDialog;
    private int actionType;
    private SignsOfDataInfo signsOfDataInfo;
    private DataClass dataClass;

    @Override
    protected void registerEvent(CommonEvent commonevent) {
        switch (commonevent.getCode()) {
            case EventCode.UNBUNDLE:
                EventBusUtil.sendEvent(new CommonEvent(EventCode.UN_DEVICE_BIND));
                EventBusUtil.sendEvent(new CommonEvent(EventCode.PERSONAGE_UP_DATA));
                dataManager.deleteAppConfigurationInfo(UserContent.UserName);
                finish();
                break;
        }
    }

    @Override
    protected void initInject() {
        getActivityComponent().inject(this);
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_multitype;
    }

    @Override
    protected void initClass() {
        showDialog = ShowDialog.newInstance();
        dataClass = new DataClass(dataManager);
    }

    @Override
    protected void initData() {
        actionType = Integer.valueOf(getIntent().getStringExtra("ActionType"));

    }

    @Override
    protected void initView() {
        switch (actionType) {
            case EventCode.UNBUNDLE://解绑
                unbundle_layout.setVisibility(View.VISIBLE);
                title_name.setText(getString(R.string.unbundle));
                initBindSetting();
                break;
            case EventCode.SET_A_GOAL://设置目标
                goal_layout.setVisibility(View.VISIBLE);
                title_name.setText(getString(R.string.set_a_goal));
                initGoal();
                break;
            case EventCode.ABOUT_://关于
                about_layout.setVisibility(View.VISIBLE);
                title_name.setText(getString(R.string.about_));
                initAbout();
                break;
            case EventCode.WEB://使用帮助(web)
                web_layout.setVisibility(View.VISIBLE);
                title_name.setText(getString(R.string.usinghelp));
                initWebView();
                break;
            case EventCode.CALORY://卡路里消耗
                calory_layout.setVisibility(View.VISIBLE);
                title_name.setText(getString(R.string.calory));
                initCalory();
                break;
            case EventCode.HEALTHTIP://健康提示
                text_layout.setVisibility(View.VISIBLE);
                title_name.setText(getString(R.string.health_tip));
                initTextContent();
                break;
            case EventCode.PULSE_CONDITION_CONTENT://脉诊详情
                pulse_condition_layout.setVisibility(View.VISIBLE);
                title_name.setText(getString(R.string.health_tip));
                initOulseConditionLayout();
                break;
        }
    }

    @Override
    protected void initListener() {
        img_btn_black.setOnClickListener(this);
        unbundle.setOnClickListener(this);
        commit.setOnClickListener(this);
        layout_app.setOnClickListener(this);
        layout_device.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.img_btn_black:
                finish();
                break;
            case R.id.unbundle:
                showDialog.showStatusDialog(this, EventCode.UNBUNDLE);
                break;
            case R.id.commit:
                try {
                    dataManager.UpDataSignsOfDataInfo(new SignsOfDataInfo(signsOfDataInfo.getId(), signsOfDataInfo.getUserName(), signsOfDataInfo.getUserPhoto(), signsOfDataInfo.getNickName(),
                            signsOfDataInfo.getSex(), signsOfDataInfo.getBirthday(), signsOfDataInfo.getHeight(), signsOfDataInfo.getWeight()
                            , signsOfDataInfo.getBrachium(), Integer.valueOf(pedometer.getText().toString().replace(" ", "")), Integer.valueOf(calory_.getText().toString().replace(" ", "")),
                            signsOfDataInfo.getPvhMmHgStandard(), signsOfDataInfo.getLdoMmHgStandard()));
                    showDialog.showStatusDialog(this, EventCode.SUCCESSFUL_UP);
                } catch (Exception e) {
                    e.printStackTrace();
                    CommonUtils.showToast(this, "保存失败，请检查是否存在空格");
                }
                break;
            case R.id.layout_app:

                break;
            case R.id.layout_device:

                break;

        }
    }

    private void initTextContent() {
        text_view.setText("温馨提示");
    }

    private void initBindSetting() {
        AppConfigurationInfo appConfigurationInfo = dataManager.queryAppConfigurationInfo(UserContent.UserName);
        if (appConfigurationInfo != null) {
            devicename.setText(appConfigurationInfo.getDeviceName());
            mac_location.setText(appConfigurationInfo.getMAC());
        } else {
            devicename.setText("");
            mac_location.setText("");
        }
    }

    private void initCalory() {
        SignsOfDataInfo signsOfDataInfo = dataManager.querySignsOfDataInfo(UserContent.UserName);
        int caloryStandard = signsOfDataInfo.getCaloryStandard();
        LogUtil.e(TAG, "caloryStandard : " + caloryStandard);
        progress_calory_bar.setMaxValue(caloryStandard);
        progress_calory_bar.setValue(DataClass.TotalCalories);
        calory_standard.setText(new StringBuffer().append(caloryStandard).append("\n千卡"));
        consume_calory.setText(String.valueOf(DataClass.TotalCalories));
        consume_calory_percentage.setText(formatData(DataClass.TotalCalories, caloryStandard));
    }

    private void initGoal() {
        signsOfDataInfo = dataManager.querySignsOfDataInfo(UserContent.UserName);
        pedometer.setText(String.valueOf(signsOfDataInfo.getStepCountStandard()));
        calory_.setText(String.valueOf(signsOfDataInfo.getCaloryStandard()));
    }

    private void initWebView() {
        web_view.setWebChromeClient(webChromeClient);
        web_view.setWebViewClient(webViewClient);
        WebSettings webSettings = web_view.getSettings();
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        webSettings.setSupportZoom(true);
        webSettings.setBuiltInZoomControls(true);
        webSettings.setDisplayZoomControls(false);
        web_view.loadUrl("https://home.firefoxchina.cn/");
    }

    private void initOulseConditionLayout() {
        Bundle extras = getIntent().getExtras();
        String biaoxian = extras.get("biaoxian").toString();
        String jianyi = extras.get("jianyi").toString();
        String maili = extras.get("maili").toString();
        String pingji = extras.get("pingji").toString();
        String type = extras.get("type").toString();
        String zhengzhaung = extras.get("zhengzhaung").toString();
        String TitleAdvice = extras.get("TitleAdvice").toString();
        String Tupian = extras.get("Tupian").toString();

        if (type.equals("xin")) {
            title_content.setText(new StringBuffer().append("心脉 : " + maili));
        } else if (type.equals("shen")) {
            title_content.setText(new StringBuffer().append("肾脉 : " + maili));
        } else if (type.equals("gan")) {
            title_content.setText(new StringBuffer().append("肝脉 : " + maili));
        }
        type_mai.setText(maili);
        type_mai_content.setText(biaoxian);
        type_zhengzhuang_content.setText(zhengzhaung);
        type_pingfen_content.setText(pingji);
        jianyi_title.setText(TitleAdvice);
        //jianyi_title.setVisibility(View.GONE);
        jianyi_content.setText(jianyi);
        jianyi_content.setVisibility(View.GONE);
        Glide.with(this).load(Tupian).into(jianyi_img);
    }

    private WebViewClient webViewClient = new WebViewClient() {

        @Override
        public void onPageFinished(WebView view, String url) {//页面加载完成
            progressbar.setVisibility(View.GONE);
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {//页面开始加载
            progressbar.setVisibility(View.VISIBLE);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (url.equals("http://www.google.com/")) {
                toastUtil.showToast("国内不能访问google,拦截该url");
                return true;//表示我已经处理过了
            }
            return super.shouldOverrideUrlLoading(view, url);
        }
    };

    private WebChromeClient webChromeClient = new WebChromeClient() {
        //不支持js的alert弹窗，需要自己监听然后通过dialog弹窗
        @Override
        public boolean onJsAlert(WebView webView, String url, String message, JsResult result) {
            AlertDialog.Builder localBuilder = new AlertDialog.Builder(webView.getContext());
            localBuilder.setMessage(message).setPositiveButton("确定", null);
            localBuilder.setCancelable(false);
            localBuilder.create().show();
            //注意:必须要这一句代码:result.confirm()表示: 处理结果为确定状态同时唤醒WebCore线程 否则不能继续点击按钮
            result.confirm();
            return true;
        }

        //获取网页标题
        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
        }

        //加载进度回调
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            if (progressbar != null)
                progressbar.setProgress(newProgress);
        }
    };

    private String formatData(int num1, int num2) {
        NumberFormat numberFormat = NumberFormat.getInstance();
        // 设置精确到小数点后2位
        numberFormat.setMaximumFractionDigits(2);
        return numberFormat.format((float) num1 / (float) num2 * 100) + "%";
    }

    private void initAbout() {
        device_version.setText(DataClass.FirmwareVersion);
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (web_view.canGoBack() && keyCode == KeyEvent.KEYCODE_BACK) {//点击返回按钮的时候判断有没有上一页
            web_view.goBack(); // goBack()表示返回webView的上一页面
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //释放资源
        if (web_view != null) {
            web_view.destroy();
            web_view = null;
        }
    }
}
